﻿
''' <summary>
''' Specifies a binary byte order to use when reading or writing values.
''' </summary>
Public Enum ByteOrder As SByte
    LittleEndian = 0
    BigEndian = 1
End Enum

''' <summary>
''' Contains static methods to swap values in byte order.
''' </summary>
Public NotInheritable Class EndianSwap
    Public Shared Function SwapToInt64(buf As Byte(), order As ByteOrder) As Long
        If order = ByteOrder.BigEndian Then
            Return (buf(0) << 56) Or (buf(1) << 48) Or (buf(2) << 40) Or (buf(3) << 32) Or (buf(4) << 24) Or (buf(5) << 16) Or (buf(6) << 8) Or buf(7)
        Else
            Return (buf(7) << 56) Or (buf(6) << 48) Or (buf(5) << 40) Or (buf(4) << 32) Or (buf(3) << 24) Or (buf(2) << 16) Or (buf(1) << 8) Or buf(0)
        End If

    End Function
    Public Shared Function SwapToInt32(buf As Byte(), order As ByteOrder) As Integer
        If order = ByteOrder.BigEndian Then
            Return (buf(0) << 24) Or (buf(1) << 16) Or (buf(2) << 8) Or buf(3)
        Else
            Return (buf(3) << 24) Or (buf(2) << 16) Or (buf(1) << 8) Or buf(0)
        End If
    End Function
    Public Shared Function SwapToSingle(buf As Byte(), order As ByteOrder) As Single
        If order = ByteOrder.BigEndian Then
            Dim test As Byte() = BitConverter.GetBytes(CInt((buf(0) << 24) Or (buf(1) << 16) Or (buf(2) << 8) Or buf(3)))
            Return BitConverter.ToSingle(test, 0)
        Else
            Dim test As Byte() = BitConverter.GetBytes(CInt((buf(3) << 24) Or (buf(2) << 16) Or (buf(1) << 8) Or buf(0)))
            Return BitConverter.ToSingle(test, 0)
        End If
    End Function
    Public Shared Function SwapToInt16(buf As Byte(), order As ByteOrder) As Short
        If order = ByteOrder.BigEndian Then
            Return CShort((buf(0) << 8) Or buf(1))
        Else
            Return CShort((buf(1) << 8) Or buf(0))
        End If
    End Function
    Public Shared Sub ByteSwap(bytes As Byte())
        Array.Reverse(bytes)
    End Sub
    Public Shared Function ReverseString(str As String) As String
        Return str.Reverse
    End Function
End Class
'public sealed class Bitwise
'{
'    public static short SetFlag(short a, short b)
'    {
'        return (short)(a | b);
'    }

'    public static short UnsetFlag(short a, short b)
'    {
'        return a & (~b);
'    }

'    // Works with "None" as well
'    public static bool HasFlag(short a, short b)
'    {
'        return (a & b) == b;
'    }

'    public static short ToogleFlag(short a, short b)
'    {
'        return a ^ b;
'    }
'}
